﻿/*******************************************************
 *  单词列表 相关操作js
 * <p>Title: wordManager.js</p>
 * <p>Description:TODO</p>
 * @author Joychen
 * @date 2019年8月6日 下午5:41:57
 * @version 1.0
 * *****************************************************/
var $table, unitzTree, options,//树控件
    selNode = null,//选中节点
    indexForm,
    checkNodeSpan = null;//选中树id;
var wordManager = {
    //1.0 初始化页面
    initPage: function () {
        parent.showLoadBoxs();
        wordManager.initSelect();
        wordManager.bindZtree();
        wordManager.bindEvent();
        wordManager.initTable();
        parent.delLoadBoxs();
    },
    //1.1 采用Ztree初始化文档树
    bindZtree: function () {
        var setting = {
            view: {
                showIcon: true,
                selectedMulti: false,
                fontCss: getFontCss
            },
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false
            },
            async: {
                enable: true,
                dataType: "text",
                type: "post",
                url: ctx + "/DocManager/GetDocTreeData?isNum=1&pro_type=3",
                autoParam: ["id"]
            },
            data: {
                key: { title: "name", name: "name" },
                simpleData: { enable: true, idKey: "id", pIdKey: "pId", rootPId: 0 }
            },
            check: {
                enable: false,
                autoCheckTrigger: true,
                chkStyle: "checkbox",
                chkboxType: { "Y": "p", "N": "ps" }
            },
            callback: {
                onAsyncError: function () {
                    layer.msg("初始化单位结构树失败~", { icon: 5 });
                },
                onAsyncSuccess: function (event, treeId, treeNode, msg) {
                    //树加载完成后执行
                    var obj = unitzTree.getNodes()[0];
                    if (obj) {
                        unitzTree.selectNode(obj);
                        unitzTree.setting.callback.onClick(null, unitzTree.setting.treeId, obj);//模拟点击事件 
                        if (obj.children && obj.children.length > 0)
                            unitzTree.expandNode(obj);
                    }
                },
                onClick: function (event, treeId, treeNode) {
                    //绑定课件下拉
                    if (!selNode || selNode.id != treeNode.id) 
                        wordManager.bindClass(treeNode.id);
                    $('#unitTree a').css("color", "#333");
                    $('#' + treeNode.tId + '_a').css("color", "#ffffff");
                    checkNodeSpan = treeNode.tId + '_span';
                    selNode = treeNode;//选中节点
                    if ($table && treeNode.id > 0)
                        $table.bootstrapTable('refresh', options);//刷新Table
                }
            }
        };
        unitzTree = $("#unitTree").initzTreeView(setting, 'ushow');
    },
    //1.2 初始化Table
    initTable: function () {
        options = {
            url: ctx + "/HeadManager/InitWordTable",
            cutHeight: 50,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            singleSelect: false,//多选
            toolbar: "#exampleToolbar",
            queryParams: function (params) {
                params = {
                    rows: params.limit,
                    //页面大小  
                    page: params.offset / params.limit + 1,
                    keyword: $('#keyword').val(),
                    file_id: ($('#fileId')) ? $('#fileId').val() : 0, //课件
                    cp_id: ($('#cpId')) ? $('#cpId').val() : 0 //关卡
                }
                return params;
            },
            columns:[
            {
                checkbox: true
            },{
                field: '',
                title: '序号',
                align: 'center',
                width: 50,
                formatter: function (value, row, index) {                     
                    return index + 1;
                }
            }, {
                field: 'file_name',
                title: '课件标题',
                align: 'center',
                width: 110,
                formatter: function (value, row, index) {
                    if (value && value.toString().length > 10)
                        back = "<span title='" + value + "'>" + value.toString().substring(0, 10) + "...</span>";
                    else
                        back = value;
                    return back;
                }
            }, {
                field: 'cp_name',
                title: '关卡名称',
                align: 'left',
                width: 110,
                formatter: function (value, row, index) {
                    if (value && value.toString().length > 10)
                        back = "<span title='" + value + "'>" + value.toString().substring(0, 10) + "...</span>";
                    else
                        back = value;
                    return back;
                }
            }, {
                field: 'word',
                title: '单词名称',
                align: 'center',
                width: 100
            }, {
                field: 'gj_symbol',
                title: '国际音标',
                align: 'center',
                width: 100
            }, {
                field: 'kk_symbol',
                title: 'KK音标',
                align: 'center',
                width: 100
            }, {
                field: 'cp_type',
                title: '词性',
                align: 'center',
                width: 100,
                formatter: function (value, row, index) {
                if (value && value.toString().length > 10)
                    back = "<span title='" + value + "'>" + value.toString().substring(0, 10) + "...</span>";
                else
                    back = value;
                return back;
            }
            }, {
                field: 'china_mean',
                title: '中文解释',
                align: 'center',
                width: 120,
                formatter: function (value, row, index) {
                    if (value && value.toString().length > 10)
                        back = "<span title='" + value + "'>" + value.toString().substring(0, 10) + "...</span>";
                    else
                        back = value;
                    return back;
                }
            }, {
                field: 'update_name',
                title: '最后修改人',
                align: 'center',
                width: 80
            }, {
                field: 'update_date',
                title: '最后修改时间',
                align: 'center',
                width: 100
            }, {
                field: 'create_name',
                title: '创建人',
                align: 'center',
                width: 80
            }, {
                field: 'create_date',
                title: '创建时间',
                align: 'center',
                width: 100
            }],
            onClickRow: function (row, $element) {
            },
            onLoadSuccess: function (data) {
            }
        }
        $table = tableHelper.initTable("exampleTableToolbar", options);
    },
    //1.3 事件绑定
    bindEvent: function () {
        //查询
        $('#btnSearch').on('click',function () {
            $table.bootstrapTable('refresh', options);
        });
        //新增
        $('#btnAdd').on('click', function () {
            wordManager.editForm();
        });
        //编辑
        $('#btnEditFile').on('click', function () {
            var row = wordManager.selections();
            if (!row)
                return false;
            wordManager.editForm(row);
        });
        //删除
        $('#btnDeleteFile').on('click', function () {
            var row = wordManager.selections(true);
            if (!row || row.length<=0)
                return false;
            layer.confirm('您确定要删除当前选择关卡？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                var index = layer.msg("删除中...", { icon: 6, time: 6000 });
                var pwId = new Array();
                $.each(row, function (index, item) {
                    pwId.push(item.pw_id);
                });
                $.ajax({
                    type: 'post',
                    url: ctx + '/HeadManager/DelWordPass',
                    dataType: 'json',
                    data:{pwId:pwId.join(',')},
                    async: false,
                    success: function (data) {
                        if (index)
                            layer.close(index);
                        if (data.Statu === 0) {
                            layer.msg("删除成功...");
                            $table.bootstrapTable('refresh', options);
                        }
                        else
                            layer.msg(data.Msg, { icon: 5 });
                    }
                });
            }, function () { });
        });
        //课件改变事件
        $('#fileId,#file_id').on('change', function () {
            var file_id = $(this).val(), $id = $(this).attr("id");
            if (!file_id) {
                if ($id === "fileId") {
                    $("#cpId").empty();
                    $('#cpId').selectpicker('refresh');
                    return false;
                } else {
                    $('#cp_id').empty();
                    $('#cp_id').selectpicker('refresh');
                    return false;
                }
            }
            $.ajax({
                type: 'post',
                url: ctx + '/HeadManager/GetPassInfo/' + file_id,
                dataType: 'json',
                async: false,
                success: function (data) {
                    if (data.Statu === 0) {
                        var itemStr = "<option value=''>全部</option>";
                        $.each(data.Data, function (i, item) {
                            if (i === 0)
                                itemStr += "<option value='" + item.value + "' selected=''>" + item.text + "</option>";
                            else
                                itemStr += "<option value='" + item.value + "'>" + item.text + "</option>";
                        });
                        if ($id === "fileId") {
                            $("#cpId").empty();
                            $('#cpId').selectpicker('refresh');
                            $('#cpId').append(itemStr);
                            $('#cpId').selectpicker('refresh');  
                        } else {
                            //添加
                            $("#cp_id").empty();
                            $('#cp_id').selectpicker('refresh');
                            $('#cp_id').append(itemStr);
                            $('#cp_id').selectpicker('refresh');
                        }
                    }
                    else
                        layer.msg(data.Msg, { icon: 5 });
                }
            });
        });
        //课件改变（全部课件）单词移动
        $('#fileClass').on('change', function () {
            var file_id = $(this).val();
            if (!file_id) {
                $("#cpClass").empty();
                $('#cpClass').selectpicker('refresh');
                return false;
            }
            $.ajax({
                type: 'post',
                url: ctx + '/HeadManager/GetPassInfo/' + file_id,
                dataType: 'json',
                async: false,
                success: function (data) {
                    if (data.Statu === 0) {
                        var itemStr = "";
                        $.each(data.Data, function (i, item) {
                            if (i === 0)
                                itemStr += "<option value='" + item.value + "' selected=''>" + item.text + "</option>";
                            else
                                itemStr += "<option value='" + item.value + "'>" + item.text + "</option>";
                        });
                        $("#cpClass").empty();
                        $('#cpClass').selectpicker('refresh');
                        $('#cpClass').append(itemStr);
                        $('#cpClass').selectpicker('refresh');
                        if(data.Data.length>0){
                            if (data.Data.length > 6)
                                $('#cpClass').selectpicker({ size: 6 });
                            else if(data.Data.length>1)
                                $('#cpClass').selectpicker({ size: data.Data.length - 1 });
                            else 
                                $('#cpClass').selectpicker({ size: data.Data.length });
                        }
                    }
                    else
                        layer.msg(data.Msg, { icon: 5 });
                }
            });
        });
        //移动单词
        $('#btnMove').on('click', function () {
            //收集需要移动的单词
            var row = wordManager.selections(true);
            if (!row)
                return false;
            var $fileClass = $('#fileClass').val(), $cpClass = $('#cpClass').val();
            if (!$fileClass) {
                layer.msg("请选择需要移动的课件！");
                return false;
            }
            if (!$cpClass) {
                layer.msg("请选择需要移动的关卡！");
                return false;
            }
            var $fileVal = $('#fileClass').find("option:selected").text(), $cpVal = $('#cpClass').find("option:selected").text();
            var wp_id = new Array();
            $.each(row, function (index,item) {
                wp_id.push(item.pw_id);
            });
            var layerIndex = layer.msg('数据处理中...', { icon: 16, shade: [0.3, '#393D49'], time: 0 });
            $.ajax({
                type: 'post',
                url: ctx + '/HeadManager/MoveWord',
                dataType: 'json',
                async: false,
                data: { file_id: $fileClass, file_name: $fileVal, cp_id: $cpClass, cp_name: $cpVal, wp_id: wp_id },
                success: function (data) {
                    layer.close(layerIndex);
                    if (data.Statu === 0) {
                        $table.bootstrapTable('refresh', options);
                        layer.msg("单词移动成功！", { icon: 1 });
                    }
                    else
                        layer.msg(data.Msg, { icon: 5 });
                }
            });
        });
        //导入
        $('#btnImportAdd').on('click', function () {
            //清空表单
            $('#importFormTable').resetHideValidForm();
            //打开导入
            layer.open({
                title: ['导入单词', 'font-size:18px;'],
                type: 1,
                content: $('#import_form'),
                scroll: true,//是否显示滚动条、默认不显示
                btn: ['确定', '取消'],
                area: ['480px', '400px'],
                success: function(li,o){
                    $('#in_file_id').selectpicker('refresh');
                },
                yes: function (li, o) {
                    //判断课件
                    var in_file_id = $('#in_file_id').val();
                    if (!in_file_id) {
                        layer.msg("导入之前请选择单词所在课件！", { icon: 5 });
                        return false;
                    }
                    $('#in_file_name').val($('#in_file_id').find("option:selected").text());
                    //判断文件
                    var fileSize = $("#excelFile")[0].files;
                    if (fileSize.length <= 0) {
                        layer.alert('请选择导入文件！', { icon: 5 });
                        return false;
                    }
                    if ($('#orgFormTable').valid()) {
                        //验证通过
                        $('#importFormTable').ajaxSubmit({
                            url: ctx + "/HeadManager/ImportWordPass",
                            type: "post",
                            dataType: "json",
                            beforeSubmit: function (arr, $form, options) {
                                layer.msg("提交数据~", { icon: 1, time: 5000 });
                            },
                            success: function (result, status, xhr, $form) {
                                if (result.Statu === 0) {
                                    layer.closeAll();
                                    $table.bootstrapTable('refresh', options);
                                    layer.alert(result.Msg, { icon: 1 });
                                }
                                else {
                                    if (result.Data) {
                                        var str = "";
                                        for (var i = 0; i < result.Data.length; i++) {
                                            str += result.Data[i] + "、";
                                        }
                                        layer.alert(str, { icon: 5 });
                                    } else
                                        layer.alert(result.Msg, { icon: 5 });
                                }
                            },
                            error: function (xhr, status, error, $form) {
                                layer.msg("保存失败~", { icon: 5 });
                            }
                        });
                    }
                },
                cancel: function (li, o) {

                }
            });
        });
    },
    //1.3.1 绑定下拉
    initSelect: function () {
        //全部课件
        //$.ajax({
        //    type: 'post',
        //    url: ctx + '/HeadManager/GetClassInfo/' + 0,
        //    dataType: 'json',
        //    async: false,
        //    success: function (data) {
        //        if (data.Statu === 0) {
        //            var itemStr = "";
        //            $.each(data.Data, function (i, item) {
        //                if (i === 0)
        //                    itemStr += "<option value='" + item.value + "' selected=''>" + item.text + "</option>";
        //                else
        //                    itemStr += "<option value='" + item.value + "'>" + item.text + "</option>";
        //            });
        //            $('#fileClass').append(itemStr);
        //            $('#fileClass').selectpicker('refresh');
        //            $('#file_id').append(itemStr);
        //            $('#file_id').selectpicker('refresh');
        //            $('#selectpicker').selectpicker({ size: 5 });
        //        }
        //        else
        //            layer.msg(data.Msg, { icon: 5 });
        //    }
        //});
        //初始化file file-pretty
        $('.files').prettyFile();
    },
    //1.4 获取被选中节点
    getSelNode: function () {
        //获取页面doc_type参数
        //获取节点folder_id参数
        var zTree = $.fn.zTree.getZTreeObj("unitTreezTreeData");
        if (!zTree)
            return null;
        var nodes = zTree.getSelectedNodes(),
           treeNode = nodes[0];
        return treeNode;
    },
    //1.5 获取被选中节点
    selections: function (isAll) {
        var row = $table.bootstrapTable('getSelections');
        if (!row || row.length === 0) {
            layer.msg("数据为空或未选中记录行~", { icon: 5 });
            return false;
        }
        if (isAll)
            return row;
        if (row.length > 1) {
            layer.msg("当前操作不支持多选，请选择一行再操作！", { icon: 5 });
            return false;
        }
        return row[0];
    },
    //1.6 添加、编辑
    editForm: function (row) {
        var $title = "添加关卡单词";
        if (!row)
            addOrEditUrl = ctx + "/HeadManager/AddWordPass";//新增
        else {
            addOrEditUrl = ctx + "/HeadManager/EditWordPass";//编辑
            $title = "编辑关卡单词";
        }
        //清空表单
        $('#orgFormTable').resetHideValidForm();
        //打开编辑
        layer.open({
            title: [$title, 'font-size:18px;'],
            type: 1,
            content: $('#org_form'),
            scroll: true,//是否显示滚动条、默认不显示
            btn: ['确定', '取消'],
            area: ['480px', '90%'],
            success: function (li, o) {
                $('#file_id').selectpicker('refresh'); 
                $('#cp_id').selectpicker('refresh');
                if (row != null) {
                    $('#orgFormTable')[0].reset();//重置表单
                    $('#orgFormTable').LoadForm(row);//表单填充数据
                }
            },
            yes: function (li, o) {
                //判断课件
                var file_id = $('#file_id').val(), cp_id = $('#cp_id').val();
                if (!file_id) {
                    layer.msg("请选择单词所在课件！", { icon: 5 });
                    return false;
                }
                if (!cp_id) {
                    layer.msg("请选择单词所在关卡！", { icon: 5 });
                    return false;
                }
                var fileName = $('#file_id').find("option:selected").text();
                if (fileName.indexOf("【") > -1)
                    fileName = fileName.substring(0, fileName.indexOf("【"));
                $('#file_name').val(fileName);
                $('#cp_name').val($('#cp_id').find("option:selected").text());
                if ($('#orgFormTable').valid()) {
                    //验证通过
                    $('#orgFormTable').ajaxSubmit({
                        url: addOrEditUrl,
                        type: "post",
                        dataType: "json",
                        beforeSubmit: function (arr, $form, options) {
                            layer.msg("提交数据~", { icon: 1, time: 5000 });
                        },
                        success: function (result, status, xhr, $form) {
                            if (result.Statu === 0) {
                                layer.closeAll();
                                $table.bootstrapTable('refresh', options);
                                layer.msg('保存成功', { icon: 1 });
                            }
                            else
                                layer.alert(result.Msg, { icon: 5 });
                        },
                        error: function (xhr, status, error, $form) {
                            layer.msg("保存失败~", { icon: 5 });
                        }
                    });
                }
            },
            cancel: function (li, o) {

            }
        });
    },
    //1.7 绑定课件下拉
    bindClass: function (folder_id) {
        $.ajax({
            type: 'post',
            url: ctx + '/HeadManager/GetClassInfo/' + folder_id,
            dataType: 'json',
            data: { notStatus: 2 }, //数据没有实际意义，仅仅表示大于0 需要排除审核未通过的记录
            async: false,
            success: function (data) {
                if (data.Statu === 0) {
                    var itemStr = "";
                    $.each(data.Data, function (i, item) {
                        if (i === 0)
                            itemStr += "<option value='" + item.value + "' selected=''>" + item.text + "</option>";
                        else
                            itemStr += "<option value='" + item.value + "'>" + item.text + "</option>";
                    });
                    //判断导入按钮是否可用
                    if(data.Data && data.Data.length>0){
                        $('#btnAdd').removeAttr("disabled");
                        $('#btnImportAdd').removeAttr("disabled");
                    }
                    else {
                        $('#btnAdd').attr("disabled", "disabled");
                        $('#btnImportAdd').attr("disabled", "disabled");
                    }
                    //*****************
                    $('#fileId').empty();
                    $('#fileId').selectpicker('refresh');
                    $('#fileId').append(itemStr);
                    $('#fileId').selectpicker('refresh');
                    $('#fileId').trigger("change");
                    //添加时绑定课件
                    $('#file_id').empty();
                    $('#file_id').selectpicker('refresh');
                    $('#file_id').append(itemStr);
                    $('#file_id').selectpicker('refresh');
                    $('#file_id').trigger("change");
                    //导入时绑定课件
                    $('#in_file_id').empty();
                    $('#in_file_id').selectpicker('refresh');
                    $('#in_file_id').append(itemStr);
                    $('#in_file_id').selectpicker('refresh');
                    $('#in_file_id').trigger("change");
                }
                else
                    layer.msg(data.Msg, { icon: 5 });
            }
        });
        //*****移动课件
        $.ajax({
            type: 'post',
            url: ctx + '/HeadManager/GetClassInfo/' + folder_id,
            dataType: 'json',
            data: { fileStatus: 5,notStatus: 2 },
            async: false,
            success: function (data) {
                if (data.Statu === 0) {
                    var itemStr = "";
                    $.each(data.Data, function (i, item) {
                            itemStr += "<option value='" + item.value + "'>" + item.text + "</option>";
                    });
                    //移动课件选择
                    $("#fileClass").empty();
                    $('#fileClass').selectpicker('refresh');
                    $('#fileClass').append(itemStr);
                    $('#fileClass').selectpicker('refresh');
                }
                else
                    layer.msg(data.Msg, { icon: 5 });
            }
        });
    }
}